package com.ld.security.common.mybatis;


import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.ld.security.common.core.util.SpringUtil;
import com.ld.security.common.mybatis.core.DsArgsProcessor;
import com.ld.security.common.mybatis.util.DataSourceUtil;
import com.ld.security.common.mybatis.wrapper.SimpWrapperFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

@Configuration

@ComponentScan("com.ld.security.common.mybatis")
@MapperScan("com.ld.security.common.mybatis.base.mapping")
public class MybatisPlusConfig {

    @Autowired
    DataSource dataSource;


    @PostConstruct
    public void DataSourceUtil(){
        DataSourceUtil.setDynamicRoutingDataSource((DynamicRoutingDataSource)dataSource);

    }

    @ConditionalOnMissingBean
    @Bean
    public DsArgsProcessor DsArgsProcessor(){

        return new DsArgsProcessor();

    }



    @ConditionalOnMissingBean
    @Bean
    public SimpWrapperFactory SimpWrapperFactory(){
        return new SimpWrapperFactory();

    }


    @ConditionalOnMissingBean
    @Bean
    public SpringUtil springUtil(){
        return new SpringUtil();
    }

    /**
     * 分页插件
     */
    @Bean
    @ConditionalOnMissingBean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    /**
     * sql注入器  逻辑删除插件
     * @return
     */
    @ConditionalOnMissingBean
    @Bean
    public ISqlInjector iSqlInjector(){
        return new LogicSqlInjector();
    }

    /**
     * sql性能分析插件，输出sql语句及所需时间
     * @return
     */
    @Bean
    @Profile({"dev","test"})// 设置 dev test 环境开启
    @ConditionalOnMissingBean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }
    /**
     * 乐观锁插件
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public OptimisticLockerInterceptor optimisticLockerInterceptor(){
        return new OptimisticLockerInterceptor();
    }


}
